package com.we823.project.core.web.security.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.we823.project.model.UserModel;
import com.we823.project.repository.service.UserService;

public class CustomRealm extends AuthorizingRealm implements ApplicationContextAware {

	private Logger logger = LoggerFactory.getLogger(CustomRealm.class);
	
	private ApplicationContext applicationContext;
	@Override
	@Autowired
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		logger.debug("doGetAuthorizationInfo");
		String username = (String) principalCollection.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		
		UserService userService = applicationContext.getBean(UserService.class);
		if (userService!=null) {
			UserModel userModel = userService.findByUsername(username);
			authorizationInfo.setRoles(userService.findStringRole(userModel));
			authorizationInfo.setStringPermissions(userService.findStringPermission(userModel));
		}
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		logger.debug("doGetAuthenticationInfo");
		if(authenticationToken!=null){
			String username = (String)authenticationToken.getPrincipal();
			UserService userService = applicationContext.getBean(UserService.class);
			if(userService!=null){
				UserModel userModel = userService.findByUsername(username);
				if(userModel!=null){
					SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
							userModel.getUsername(),
							userModel.getPassword(),
							getName()
							);
					return simpleAuthenticationInfo;
				}
			}
		}
		return null;
	}

}
